<template>
  <a-space>
    <qc-save-button
      :loading="btnLoading"
      type="primary"
      :disabled="checkedKeys.length == 0"
      @click="saveRoleInterfaceCheckedKeyList"
    ></qc-save-button>
  </a-space>
  <div>
    <a-tree
      ref="actionTreeRef"
      checkable
      :tree-data="treeData"
      :replaceFields="replaceFields"
      :defaultExpandAll="false"
      v-model:checkedKeys="checkedKeys"
    >
      <template #custom="item">
        <span style="margin-right: 10px">
          {{ item.actionName }}
        </span>
        <a-tag>{{ item.authorityKey }}</a-tag>
      </template>
    </a-tree>
  </div>
</template>

<script lang='ts'>
import { defineComponent, nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import { RESOURCE_TYPE, RESOURCE_CATEGORY } from './interface'
import resourceAuthorityApi from '/@/api/org/resource-authority'
import appActionApi from '/@/api/org/app-action'

export default defineComponent({
  name: 'InterfacePermission',
  props: {
    roleId: {
      //角色id
      type: String,
      required: true,
    },
  },
  setup(props) {
    const actionTreeRef = ref()
    const treeData = ref<string[]>([])
    const checkedKeys = ref<string[]>([])

    const actionPermissionState = reactive({
      btnLoading: false,
      replaceFields: {
        children: 'children',
        title: 'actionName',
        key: 'actionId',
      },
      //获取接口树
      getActionTree: () => {
        appActionApi.tree().then((res) => {
          treeData.value = res.data.data
          nextTick(() => actionPermissionState.getRoleActionResource())
        })
      },
      //获取角色已有的接口权限
      getRoleActionResource: () => {
        resourceAuthorityApi.getRoleInterfaceResource(props.roleId).then((res) => {
          checkedKeys.value = res.data.data
        })
      },
      //保存角色菜单信息
      saveRoleInterfaceCheckedKeyList: () => {
        actionPermissionState.btnLoading = true
        const resourceAuthorityList = []
        checkedKeys.value.forEach((key) => {
          resourceAuthorityList.push({
            roleId: props.roleId,
            resourceId: key,
            resourceType: RESOURCE_TYPE.INTERFACE,
            resourceCategory: RESOURCE_CATEGORY.USE,
          })
        })
        resourceAuthorityApi
          .addBatch(resourceAuthorityList, {
            roleId: props.roleId,
          })
          .finally(() => (actionPermissionState.btnLoading = false))
      },
    })

    onMounted(() => actionPermissionState.getActionTree())

    return {
      actionTreeRef,
      treeData,
      checkedKeys,
      ...toRefs(actionPermissionState),
    }
  },
})
</script>